package ldh.im.fxgui;

import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import ldh.im.ImConfig;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.service.CheckHotMessageTotalService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.controller.LoginController;
import ldh.im.fxgui.controller.MainController;
import ldh.im.fxgui.service.SynDataService;
import ldh.im.fxgui.util.ImSingleton;
import ldh.im.fxgui.util.UiUtil;
import ldh.rpc.cache.CacheService;
import org.slf4j.Logger;

import java.time.LocalDateTime;

public class MainUi extends Stage {

    private static final Logger LOGGER = LoggerUtil.getFileLogger(MainUi.class);

    private Pane mainPane = null;

    public MainUi() {
        initOwner(StageUtil.getMainStage());
        initStyle(StageStyle.TRANSPARENT);
        StageUtil.setStage(this);
        mainPane = buildApp();
        CacheService cacheService = RpcUtil.getRpcBootstrap().getRpcConfig().getCacheService();
        String userId = (String) cacheService.getCache(ImConfig.LOGIN_USER_ID);
        if (userId == null) {
            showLoginPane(this);
        } else {
            ImUser user = ImCacheFactory.getInstance().getUser(userId);
            UiUtil.setLoginImUser(user);
            ThreadPoolUtil.submit(()->{
                loadData();
            });
            showMainPane();
        }
        this.setOnCloseRequest(e->{
            closeUi();
        });
    }

    private void closeUi() {
        LOGGER.info("main ui close!!!!!!!!!!!!!!!!!!!!!!!");
        StageUtil.setStage(null);
        UiUtil.setMainController(null);
        UiUtil.setSendMessageHandler(null);
        UiUtil.setLoginImUser(null);
        ImHotMessageSingleton.getInstance().cleanCache();
    }

    public void startMainStage(Stage primaryStage) {
//        System.setProperty("javafx.application.name", "宇联通IM");
        primaryStage.getIcons().add(new Image(this.getClass().getResource("/imgs/icon.jpg").toExternalForm()));

        Scene scene = new Scene(mainPane, 900, 650);
        scene.setFill(Color.RED);

//        scene.getStylesheets().add(this.getClass().getResource("/css/login.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/var.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/stage.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/main.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/scrollbar.css").toExternalForm());
//        scene.getStylesheets().add(this.getClass().getResource("/css/window-scrollbar.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/tabpane.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/bootstrapfx.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/group.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/message-dialog.css").toExternalForm());             // 弹出框
        scene.getStylesheets().add(this.getClass().getResource("/css/user.css").toExternalForm());               // 用户管理
        scene.getStylesheets().add(this.getClass().getResource("/css/message-send.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/collect.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/setting.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/workbench.css").toExternalForm());
        primaryStage.setScene(scene);

        ResizeHelper.addResizeListener(primaryStage);
        primaryStage.show();
        primaryStage.toFront();
        // 绑定快捷键

        primaryStage.maximizedProperty().addListener(l -> {
            if (primaryStage.isMaximized()) {
                mainPane.getStyleClass().add("max-stage");
            } else {
                mainPane.getStyleClass().remove("max-stage");
            }
        });
//        ScenicView.show(scene);
    }

    private Pane buildApp() {
        RegionUtil.FxmlBean<Pane, MainController> fxmlBean = RegionUtil.loadFxmlBean(MainApp.class.getResource("/fxml/MainPage.fxml"));
        UiUtil.setMainController(fxmlBean.getController());
//        UiUtil.getEmojiPane();  // 提前实例化
        return fxmlBean.getNode();
    }

    private void showMainPane() {
        LOGGER.info("show main pane");
        UiUtil.getMainController().showMessagePane(null);
        startMainStage(this);

        LOGGER.info("show main pane end");
    }

    private void showLoginPane(Stage primaryStage) {
        RegionUtil.FxmlBean<Pane, LoginController> fxmlBean = RegionUtil.loadFxmlBean(MainApp.class.getResource("/fxml/LoginPage.fxml"));
        Scene scene = fxmlBean.getController().createScene();

        Stage stage = new Stage();
        stage.getIcons().add(new Image(this.getClass().getResource("/imgs/icon.jpg").toExternalForm()));

        stage.initOwner(StageUtil.getMainStage());
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setScene(scene);

        stage.show();

        fxmlBean.getController().setLoginStage(stage);
        fxmlBean.getController().setCallBack((Void) -> {
            try {
                loadData();

                FxThreadUtil.runLater(() -> {
                    stage.close();
                    showMainPane();
                });
            } catch (Exception e) {
                LOGGER.error("login success and do business error", e);
            }
        });

        stage.setOnCloseRequest((e)->{
            LOGGER.info("login stage close!!!!!!!!");
            fxmlBean.getController().setLoginStage(null);
            fxmlBean.getController().setCallBack(null);
            stage.setScene(null);
        });
    }

    private void loadData() {
        String userId = RpcUtil.getRpcBootstrap().getRpcConfig().getCacheService().getCache(ImConfig.LOGIN_USER_ID).toString();
        CheckHotMessageTotalService checkHotMessageTotalService = new CheckHotMessageTotalService();
        LocalDateTime startDate = LocalDateTime.now();
        startDate = startDate.plusDays(-14);
        checkHotMessageTotalService.checkHotMessageTotal(userId, startDate);

        SynDataService messageService = new SynDataService();
        messageService.synData(userId);
        LOGGER.info("synData end");
        ImCacheFactory.getInstance().loadAllUsers();
        loadLoginUser(userId);
    }

    private void loadLoginUser(String userId) {
        LOGGER.info("load login user: {}", userId);
        try {
            ImUser imUser = ImCacheFactory.getInstance().getUser(userId);
            UiUtil.setLoginImUser(imUser);
        } catch (Exception e) {
            LOGGER.error("load login user error", e);
        }
    }
}
